package com.luo90.campaign.aop;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.jdbc.core.JdbcTemplate;
import org.wltea.expression.ExpressionEvaluator;
import org.wltea.expression.datameta.Variable;

import com.luo90.campaign.cache.CampaignCache;
import com.luo90.campaign.entity.CampaignAttribute;
import com.luo90.campaign.entity.CampaignNodeInfo;
import com.luo90.campaign.CampaignExecute;
import com.luo90.utils.ReflectHelper;

@Aspect
public class CampaignAspect {
	private JdbcTemplate jdbcTemplate;
	private Map<String,CampaignExecute> executeMap;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public void setExecuteMap(Map<String, CampaignExecute> executeMap) {
		this.executeMap = executeMap;
	}

	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("进入方法---环绕通知"); 
		
		Object o = pjp.proceed();

		String nodeName = pjp.getSignature().getName();
		System.out.println("节点名称："+nodeName);
		// 获取活动配置
		Object[] obj = pjp.getArgs();
		System.out.println("param:" + obj);

		CampaignCache campaign = new CampaignCache(jdbcTemplate);
		List<CampaignNodeInfo> list = campaign
				.getCampaignNodeInfoByNode(nodeName);
		System.out.println("取得活动："+list.size());
		Date nowTime = new Date();
		for (CampaignNodeInfo info : list) {
			if(nowTime.getTime()<info.getStartTime().getTime()||nowTime.getTime()>info.getEndTime().getTime()){
				continue;
			}
			List<Variable> variables = new ArrayList<Variable>();
			for(CampaignAttribute attr:info.getInParam()){
				if("string".equals(attr.getType())){
					variables.add(Variable.createVariable(attr.getCode(), attr.getValue()));
				}else if("int".equals(attr.getType())){
					variables.add(Variable.createVariable(attr.getCode(), Integer.parseInt(attr.getValue())));
				}else if("float".equals(attr.getType())){
					variables.add(Variable.createVariable(attr.getCode(), Double.parseDouble(attr.getValue())));
				}else if("param".equals(attr.getType())){
					variables.add(Variable.createVariable(attr.getCode(), ReflectHelper.getValueByPath(obj[getIndexByParamPath(attr.getValue())],tramParamPath(attr.getValue()))));
				}
			}
			// 执行表达式
			Object result = ExpressionEvaluator.evaluate(info.getExpression(), variables);
			System.out.println("Result = " + result+";info.getResult():"+info.getResult());
			if(result.toString().equals(info.getResult())){
				System.out.println("---------达到预期，执行活动---------");
				if(executeMap!=null&&info.getExecContent()!=null){
					Map paramMap = new HashMap();
					for(CampaignAttribute attr:info.getOutParam()){
						if("string".equals(attr.getType())){
							paramMap.put(attr.getCode(), attr.getValue());
						}else if("int".equals(attr.getType())){
							paramMap.put(attr.getCode(), Integer.parseInt(attr.getValue()));
						}else if("float".equals(attr.getType())){
							paramMap.put(attr.getCode(), Double.parseDouble(attr.getValue()));
						}else if("param".equals(attr.getType())){
							paramMap.put(attr.getCode(), ReflectHelper.getValueByPath(obj[getIndexByParamPath(attr.getValue())],tramParamPath(attr.getValue())));
						}
					}
					
					for(String content:info.getExecContent().trim().split(",")){
						CampaignExecute campaignExecute = executeMap.get(content);
						if(campaignExecute!=null){
							System.out.println("---------执行活动["+content+"]---------");
							campaignExecute.execute(paramMap);
						}
					}
				}
			}else{
				System.out.println("---------未达到预期，不执行活动---------");
			}
		}

		System.out.println("退出方法---环绕通知");
		return o;
	}
	private String tramParamPath(String paramPath){
		if(paramPath.split(".").length>1){
			if(isInt(paramPath.split(".")[0])){
				return paramPath.substring(paramPath.indexOf("."));
			}else{
				return paramPath;
			}
		}else{
			return paramPath;
		}
	}
	private int getIndexByParamPath(String paramPath){
		if(paramPath.split(".").length>1){
			if(isInt(paramPath.split(".")[0])){
				return Integer.parseInt(paramPath.split(".")[0]);
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}
	/**
	 * 检查是否为数字
	 * @param param
	 * @return
	 */
	public boolean isInt(String param) {
		Pattern regex = Pattern
				.compile("[0-9]*");
		Matcher matcher = regex.matcher(param);
		return matcher.matches();
	}
}
